package com.love.marriage.cloud.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.dyplsapi20170525.Client;
import com.aliyun.dyplsapi20170525.models.*;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.love.marriage.cloud.service.AliyunDyplsService;
import com.love.marriage.config.AliyunDyplsConfig;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
@RequiredArgsConstructor
@Slf4j
public class AliyunDyplsServiceImpl implements AliyunDyplsService {

    private final AliyunDyplsConfig aliyunDyplsConfig;

    public Client createClient() throws Exception {
        // 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考。
        // 建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378657.html。
        Config config = new Config()
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
                .setAccessKeyId(aliyunDyplsConfig.getAccessKeyId())
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                .setAccessKeySecret(aliyunDyplsConfig.getAccessKeySecret());
        // Endpoint 请参考 https://api.aliyun.com/product/Dyplsapi
        config.endpoint = aliyunDyplsConfig.getRegionId();
        return new Client(config);
    }

    @Override
    public BindAxbResponseBody.BindAxbResponseBodySecretBindDTO bindPhone(String phoneA, String phoneB, String phoneX) throws Exception {
        Client client = createClient();
        BindAxbRequest bindAxbRequest = new com.aliyun.dyplsapi20170525.models.BindAxbRequest()
                .setPoolKey(aliyunDyplsConfig.getPoolKey())
                .setPhoneNoA(phoneA)
                .setPhoneNoB(phoneB)
                .setPhoneNoX(phoneX)
                .setExpiration(LocalDateTime.now().plusSeconds(300).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))
                .setIsRecordingEnabled(false)
                .setExpectCity(aliyunDyplsConfig.getExpectCity());
        RuntimeOptions runtime = new RuntimeOptions();
        try {
            // 复制代码运行请自行打印 API 的返回值
            BindAxbResponse bindAxbResponse = client.bindAxbWithOptions(bindAxbRequest, runtime);
            log.info("bindAxbResponse:{}", JSONObject.toJSONString(bindAxbResponse));
            if (bindAxbResponse.getStatusCode() == 200 && "OK".equals(bindAxbResponse.getBody().code)) {
                return bindAxbResponse.getBody().getSecretBindDTO();
            } else {
                throw new Exception(String.format("绑定失败，错误编码：%s，错误信息：%s",
                        bindAxbResponse.getBody().getCode(),
                        bindAxbResponse.getBody().getMessage()));
            }
        } catch (TeaException error) {
            log.error(error.getMessage());
            throw new Exception(error.getMessage());
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            throw new Exception(error.getMessage());
        }
    }

    @Override
    public Boolean unBindPhone(String poolKey, String SubsId, String SecretNo) throws Exception {
        Client client = createClient();
        UnbindSubscriptionRequest unbindSubscriptionRequest = new UnbindSubscriptionRequest()
                .setPoolKey(poolKey == null ? aliyunDyplsConfig.getPoolKey() : poolKey)
                .setSubsId(SubsId)
                .setSecretNo(SecretNo);
        RuntimeOptions runtime = new RuntimeOptions();
        try {
            // 复制代码运行请自行打印 API 的返回值
            UnbindSubscriptionResponse unbindSubscriptionResponse = client.unbindSubscriptionWithOptions(unbindSubscriptionRequest, runtime);
            if (unbindSubscriptionResponse.getStatusCode() == 200 && "OK".equals(unbindSubscriptionResponse.getBody().code)) {
                return true;
            } else {
                throw new Exception("解绑失败" + unbindSubscriptionResponse.getBody().getMessage());
            }
        } catch (TeaException error) {
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            throw new Exception("解绑失败" + error.getMessage());
        } catch (Exception _error) {
            throw new Exception("解绑失败" + _error.getMessage());
        }
    }
}
